<?php
class Model{
	// 属性
	public $tname;
	public $field;
	public $where;
	public $order;
	public $mysqli;
	public $limit;
	public $insert;

	// 构造函数
	function __construct($tname){
		$this->tname=$tname;
		// 连接数据库
		$this->mysqli=new mysqli(HOST,USER,PSWD,DBNAME);
		if($this->mysqli->connect_error){
			die('数据库连接出错'.$this->mysqli->connect_error);
		}		
			
	}

	// 方法

	// 字段
	function field($field){		 
		$this->field=$field;
		return $this;

	}
	// 条件
	function where($where){
		$this->where='where '.$where;
		return $this;
	}
	// 排序
	function order($order){
		$this->order='order by '.$order;
		return $this;
	}

	// 插入
	function insert($insert){
		$this->insert='values('.$insert.')';
		return $this;
	}

	//分页类
	function limit($limit){
		$this->limit=$limit;
		return $this;
	}

	// 清除属性值
	function clearAttr(){
		unset($this->field);
		unset($this->where);
		unset($this->order);
		unset($this->limit);
		unsert($this->insert);
	}

	//增、删、改、查组合
	function select(){
		// 组合sql语句并执行返回
		// $user->field()->where()->order()->select();	
		if(isset($this->field)){
			$sql="select {$this->field} from {$this->tname} {$this->where} {$this->order} {$this->limit}";	
		}else{			
			$sql="select * from {$this->tname} {$this->where} {$this->order} {$this->limit}";	
		}			
		$this->clearAttr(); //sql语句组合完毕，即可清除属性值	
		$rst=$this->mysqli->query($sql); //执行sql语句
		
		// 组合二维数组
		while($row=$rst->fetch_assoc()){
			$rows[]=$row;
		}
		return $rows; //返回二维数组
	}

	// 删除
	function delete(){
		$sql="delete from {$this->tname} {$this->where}";
		$this->clearAttr(); //sql语句组合完毕，即可清除属性值	
		//执行sql语句,如果成功返回影响行数
		if($this->mysqli->query($sql)){
			return $this->mysqli->affected_rows;
		}else{
			return false;
		}
	}

	// 增加
	function add(){			
		$sql="insert into  {$this->tname}({$this->field}) {$this->insert}";
		$this->clearAttr(); //sql语句组合完毕，即可清除属性值	
		//执行sql语句,如果成功返回影响行数
		if($this->mysqli->query($sql)){
			return $this->mysqli->affected_rows;
		}else{
			return false;
		}	
	}

	// 更新
	function update(){
		$sql="update {$this->tname} set {$this->field} {$this->where}";
		$this->clearAttr(); //清除缓存值
		//执行sql语句,如果成功返回影响行数
		if($this->mysqli->query($sql)){
			return $this->mysqli->affected_rows;
		}else{
			return false;
		}
	}

	

}

?>